package org.dean.webapps.projectname.utils;

import org.apache.commons.lang.StringUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: alex_yin
 * Date: 10/10/11
 * Time: 4:48 PM
 * To change this template use File | Settings | File Templates.
 */
public class DateUtils {
    public static Date getDayBegin(Date date){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        return cal.getTime();
    }

    public static Date getDayBefore(Date date, Integer days){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)-days);
        return cal.getTime();
    }

    public static String formatDate(Date date, String format){
        if(StringUtils.isEmpty(format)){
            format = "yyyy-MM-dd HH:mm:ss";
        }

        if(null == date){
            date = new Date();
        }

        DateFormat dateFormat = new SimpleDateFormat(format);

        String strDate = dateFormat.format(date);

        return strDate;
    }
}
